import { astUtil, findNodeById } from '@/utils';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { BetaSchemaForm, ProTable } from '@ant-design/pro-components';
import {
  Button,
  Collapse,
  Drawer,
  Form,
  message,
  Radio,
  Space,
  Switch,
} from 'antd';
import CollapsePanel from 'antd/lib/collapse/CollapsePanel';
import { cloneDeep } from 'lodash';
import PropTypes from 'prop-types';
import { FormInstance, FormProps } from 'rc-field-form';
import React, { memo, MouseEventHandler, useCallback, useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { EventProp } from '../PropsPanel/EventsPanel';
import StringProp from '../PropsPanel/StringProp';
import ColumnFormItem from './ColumnFormItem';
import { columns, DataItem, DataItemColumns } from './data';
import styles from './index.less';

const ProTablePanel: React.FC = (props: any) => {
  console.log('props -> ', props);
  const {
    project: { ast, currentCompId, pageConfig },
    saveNodeChange,
  } = props;
  const classProps = astUtil.getClassEventsByAst(ast);
  // 获取配置
  const pagerFormRef = useRef<FormInstance<any>>();
  const dataSourceFormRef = useRef<FormInstance<any>>();
  const currentComponent = findNodeById(pageConfig, currentCompId) || {} as API.Node;
  console.log('currentConponent: ', currentComponent);
  const [columnList, setColumnList] = useState<DataItem[]>([]);
  const [isShowConfigDrawer, setIsShowConfigDrawer] = useState(false);
  const showProTableEditPanel = useCallback(
    () => setIsShowConfigDrawer(true),
    [],
  );

  const handleAddColumn = useCallback(() => {
    setColumnList(
      columnList.concat({
        columnName: '',
        dataIndex: '',
        type: '',
        fix: false,
        search: false,
      }),
    );
  }, [columnList]);

  const handleSubmit = async () => {
    console.log('columnList: ', columnList);
    for (let i = 0; i < columnList.length; i++) {
      const item = columnList[i];
      if (!item?.__disabled) {
        message.warning('请先保存列设置的信息');
        return;
      }
    }
    const pageValues = await pagerFormRef.current?.validateFields();
    const dataValues = await dataSourceFormRef.current?.validateFields();
    console.log('获取提交的信息---', pageValues, dataValues);
    if (!currentComponent.events) currentComponent.events = {}; // 初始化事件绑定
    // 修改节点属性并保存
    if (dataValues) {
      currentComponent.props.dataSource = dataValues.dataSource;
      currentComponent.props.loading = dataValues.loading;
    }
    if (pageValues) {
      currentComponent.props.pagination = {
        pageSize: pageValues.pageSize,
        current: pageValues.current,
        total: pageValues.total,
      };
      // 绑定页面变动事件
      currentComponent.events.onChange = pageValues.onChange
    }
    if (Array.isArray(columnList) && columnList.length) {
      currentComponent.props.columns = columnList;
    }
    // currentComponent.props.autoFetch = dataValues.autoValue;

    console.log('currentComponent ---> ', currentComponent);
    // 保存节点信息
    saveNodeChange({payload: currentComponent});
  };

  const handleValuesChange = (__: any, params: any) => {
    console.log(params);
  };

  const handleColumnItemFormFinish = (formData: any, index: number) => {
    const newColumnItemFormList = cloneDeep(columnList);
    newColumnItemFormList[index] = formData;
    setColumnList(newColumnItemFormList);
  };

  useEffect(() => {
    if (Array.isArray(currentComponent?.props?.columns)) {
      setColumnList(currentComponent.props.columns);
    }
  }, [currentComponent?.props?.columns]);
  return (
    <>
      <div className={styles.wrap}>
        <div className={styles.editBar}>
          <Button type="link" onClick={showProTableEditPanel}>
            编辑
          </Button>
        </div>
        <ProTable
          className={styles.table}
          options={false}
          columns={columns}
          dataSource={new Array(4).fill({
            key1: '文字内容',
            key2: '文字内容',
            key3: '文字内容',
            key4: '文字内容',
          })}
        />
      </div>
      <Drawer
        visible={isShowConfigDrawer}
        onClose={useCallback(() => setIsShowConfigDrawer(false), [])}
        width={800}
        footer={
          <Space>
            <Button>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Collapse bordered={false}>
          <CollapsePanel
            header={
              <>
                <span>列设置</span>
              </>
            }
            key="columns"
          >
            <div>
              <Collapse ghost bordered={false}>
                <>
                  {columnList.map((item, index) => (
                    <CollapsePanel
                      header={
                        <div>{item.columnName || `第${index + 1}列`}</div>
                      }
                      key={index}
                      extra={
                        <MinusCircleOutlined
                          style={{ color: 'red' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            setColumnList(
                              columnList.filter((item, i) => i !== index),
                            );
                          }}
                        />
                      }
                    >
                      <ColumnFormItem
                        initFormData={item}
                        onFinish={(formData) =>
                          handleColumnItemFormFinish(formData, index)
                        }
                      />
                    </CollapsePanel>
                  ))}
                </>
              </Collapse>
              <Button
                type="dashed"
                size="large"
                icon={<PlusCircleOutlined />}
                style={{ width: '100%', marginTop: 10 }}
                onClick={handleAddColumn}
              >
                新增
              </Button>
            </div>
          </CollapsePanel>
          <CollapsePanel key="pagination" header="分页设置">
            <Form
              labelCol={{ span: 4 }}
              ref={pagerFormRef}
              onValuesChange={handleValuesChange}
            >
              <Form.Item
                label="pageSize"
                name="pageSize"
                rules={[{ required: true }]}
              >
                <StringProp name="" />
              </Form.Item>
              <Form.Item
                label="total"
                name="total"
                rules={[{ required: true }]}
              >
                <StringProp name="" />
              </Form.Item>
              <Form.Item
                label="current"
                name="current"
                rules={[{ required: true }]}
              >
                <StringProp name="" />
              </Form.Item>
              <Form.Item
                label="当前页变化"
                name="onChange"
                rules={[{ required: true }]}
              >
                <EventProp
                  name={''}
                  classProps={classProps}
                  event={''}
                  value={''}
                />
              </Form.Item>
              <Form.Item
                label="pageSize切换器"
                name="showChanger"
                rules={[{ required: true }]}
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            </Form>
          </CollapsePanel>
          <CollapsePanel header="数据源设置" key="dataSource">
            <Form labelCol={{ span: 4 }} ref={dataSourceFormRef}>
              <Form.Item
                name="dataSource"
                label="dataSource"
                rules={[{ required: true }]}
              >
                <StringProp />
              </Form.Item>
              {/* <Form.Item
                name="autoFetch"
                label="自动获取数据"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item> */}
              <Form.Item
                name="loading"
                label="loading"
                rules={[{ required: true }]}
              >
                <StringProp />
              </Form.Item>
            </Form>
          </CollapsePanel>
        </Collapse>
      </Drawer>
    </>
  );
};

ProTablePanel.propTypes = {
  second: PropTypes.string,
};

const mapStateToProps = ({ project }: any) => ({ project });

const mapDispatchToProps = {
  saveNodeChange: ({ payload }: any) => ({
    type: 'project/saveNodeChange',
    payload,
  }),
};

export default memo(connect(mapStateToProps, mapDispatchToProps)(ProTablePanel));
